package com.example.pdfandword.controller;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class DemoV1_1 {

    private static HttpURLConnection con;

    private static String urlQuery = "https://dataapi.mishishuju.com/v1.1.1/data-orders/query";

    private static String urlGetResult = "https://dataapi.mishishuju.com/v1.1.1/data-orders/get-result";

    public static void main(String[] args) throws MalformedURLException,
            ProtocolException, IOException {
        // 同步产品调用查询接口直接获取查询结果
        String urlParameters = "type=CR&products=N0132&name=徐豪&id_number=350624199710073015";
        String jsonStr = post(urlQuery, urlParameters);
        System.out.println(jsonStr);
//        JSONObject obj= JSON.parseObject(jsonStr);//将json字符串转换为json对象
//        JSONObject data = obj.getJSONObject("data");
//        String orderId = data.getString("serial_number");
//
//        // 异步产品需要根据订单号读取报告内容
//        String urlParameters = "order_id=" + orderId;
//        String jsonStr = post(urlGetResult, urlParameters);
//        System.out.println(jsonStr);
    }

    public static String post(String url, String urlParameters) throws MalformedURLException,
            ProtocolException, IOException {


        byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

        try {

            URL myUrl = new URL(url);
            con = (HttpURLConnection) myUrl.openConnection();

            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Java client");
            con.setRequestProperty("Authorization", "Bearer 4cd1869b205e0cbab64ee3d07d903908");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
                wr.write(postData);
            }

            StringBuilder content;

            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()))) {

                String line;
                content = new StringBuilder();

                while ((line = in.readLine()) != null) {
                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }

            return content.toString();

        } finally {
            con.disconnect();
        }
    }

}
